<template>
  <div class="zyEditor">
    <el-upload id="elUpload" :show-file-list="false" accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG,.PNG,.GIF"
               class="upload-demo" name="file" action="https://jsonplaceholder.typicode.com/posts/"
               :httpRequest="uploadFile" :data="{type: 'img'}" multiple>
      <zy-button id="elBtn" type="primary">点击上传</zy-button>
    </el-upload>
    <quill-editor v-model="adesc" ref="QuillEditor" class="QuillEditor" :options="editorOption" v-if="editorOption"
                  :disabled="disabled"></quill-editor>
  </div>
</template>

<script>
	import {mapGetters} from "vuex";
	// import OSS from 'ali-oss';

	export default {
		name: "zyEditor",
		props: {
			value: {
				type: String,
				default: () => ""
			},
			toolbarOptions: {
				type: Array,
				default: () => [
					["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
					//   ["blockquote", "code-block"], // 引用  代码块
					[{header: 1}, {header: 2}], // 1、2 级标题
					[{list: "ordered"}, {list: "bullet"}], // 有序、无序列表
					//   [{ script: "sub" }, { script: "super" }], // 上标/下标
					[{indent: "-1"}, {indent: "+1"}], // 缩进
					// [{'direction': 'rtl'}],                         // 文本方向
					[{size: ["small", false, "large", "huge"]}], // 字体大小
					[{header: [1, 2, 3, 4, 5, 6, false]}], // 标题
					//   [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
					[{color: []}], // 字体颜色、字体背景颜色
					//   [{ font: [] }], // 字体种类
					[{align: []}], // 对齐方式
					["clean"], // 清除文本格式
					["image", "video"] // 链接、图片、视频
				]
			},
			disabled: {
				type: Boolean,
				default: () => false
			},
			placeholder: {
				type: String,
				default: () => "您想说点什么"
			}
		},
		data() {
			return {
				loading: false,
				fileList: [],
				activeName: 'first',
				//显示插入视频链接弹框的标识
				videoUploadTag: false,
				//弹框插入的视频链接记录
				videoLink: "",
				videoSrc: '',
				adesc: '',
				editorOption: null,
			};
		},
		computed: {
			...mapGetters(["getToken", "uploadVideo"]),
			// getToken() {
			// 	return {token: this.getToken};
			// },
			// formData(){
			// 	return {
			// 		region:'https://oss-cn-shenzhen.aliyuncs.com',
			// 		accessKeyId:'LTAIgpTAJ2cp4fkS',
			// 		accessKeySecret:'DedCIb1eFd7KFrwWhRS6NHhjujMoz5',
			// 		bucket:'testyishui'
			//   }
			// }
		},
		watch: {
			value(val) {
				if (!this.adesc) {
					document.querySelector("div.ql-editor").innerHTML = val;
				}
			},
			adesc(val) {
				this.$emit('input', val)
			},
			placeholder(val) {
				this.editorOption.placeholder = val || '';
			}
		},
		components: {},
		methods: {
			beforeUpload(file) {
				this.loading = true;
			},
			removeVideo() {
				this.fileList = [];
				this.videoLink = '';
			},
			uploadFile(params) {
				let type = params.data.type;
				this.$axios.post(this.$api.uploadFile, {
					isFile: true,
					file: params.file,
					operator: 'goods',
				}).then(res => {
					if (res.code == 200) {
						this.$message.success(res.msg);
						let quill = this.$refs.QuillEditor.quill
						// 如果上传成功
						if (res) {
							// 获取光标所在位置
							let length = quill.getSelection().index
							// 插入图片，res为服务器返回的图片链接地址
							quill.insertEmbed(length, 'image', res.data.url)
							// 调整光标到最后
							quill.setSelection(length + 1)
						} else {
							// 提示信息，需引入Message
							this.$message.error('图片插入失败')
						}
					} else {
						this.$message.error(res.msg);
					}
				})
			},
			handleCustomMatcher(node, Delta) {
				let ops = [];
				Delta.ops.forEach(op => {
					if (op.insert && typeof op.insert === 'string') {// 如果粘贴了图片，这里会是一个对象，所以可以这样处理
						ops.push({
							insert: op.insert,
						})
					} else if (op.insert.image && this.adesc.indexOf(op.insert.image) == -1) {
						this.$message.error('不允许粘贴图片，请手动上传')
					} else {
						ops.push({
							insert: op.insert,
						})
					}
				});
				Delta.ops = ops;
				return Delta
			}
		},
		mounted() {
			let self = this;
			this.editorOption = {
				theme: "snow", // or 'bubble'
				placeholder: this.placeholder || '',
				modules: {
					clipboard: {
						// 粘贴版，处理粘贴时候带图片
						matchers: [[Node.ELEMENT_NODE, this.handleCustomMatcher]],
					},
					toolbar: {
						container: this.toolbarOptions,
						// container: "#toolbar",
						handlers: {
							image: function (value) {
								if (self.disabled) {
									return;
								}
								if (value) {
									this.accept = '.jpg,.jpeg,.png,.gif,.JPG,.JPEG,.PNG,.GIF';
									// 触发input框选择图片文件
									document.getElementById('elBtn').click()
								} else {
									this.quill.format('image', false)
								}
							},
							video: function (value) {
								if (self.disabled) {
									return;
								}
								self.videoUploadTag = true;
							}
						}
					}
				}
			}
		},
		created() {
		}
	}
</script>

<style scoped lang="less">
  @import "../../style/common/common";

  .upload-video {
    display: flex;
    align-items: center;
    flex-wrap: wrap;

    .tips {
      font-size: 14px;
      color: @allWarringColor;
      margin-left: 10px;
    }

    .el-upload-list {
      width: 100%;
    }
  }

  #elUpload {
    position: absolute;
    left: 0;
    right: 0;
    z-index: -1;
    visibility: hidden;
  }

  .QuillEditor {
    min-height: 300px;
    display: flex;
    flex-direction: column;

    /deep/ .ql-container {
      flex: 1;

      .ql-video {
        width: 100%;
        height: 300px;
      }
    }
  }

  iframe.ql-video video {
    video {
      width: 100% !important;
      height: 300px !important;
    }
  }
</style>
